package com.java.business.jxc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java.business.jxc.bean.B_OUTPUT;
import com.java.business.jxc.bean.B_BACK;
import com.java.business.jxc.dao.BackMapper;
import com.java.business.jxc.dao.OutputMapper;
import com.java.core.bean.LowerCaseKeyMap;
import com.java.core.utils.IdUtils;

@Transactional
@Service
public class BackService {

	@Autowired
	private BackMapper mapper;

	@Autowired
	private OutputMapper outputMapper;

	public void add(B_BACK back) throws RuntimeException {
		back.setBack_id(IdUtils.uuid());
		B_OUTPUT output = new B_OUTPUT();
		output.setBuilder_id(back.getBuilder_id());
		output.setMaterial_id(back.getMaterial_id());
		Double outputAmount = outputMapper.getOutputAmount(output);
		if (outputAmount == 0) {
			throw new RuntimeException("该施工队没有出库该材料，无法退库！");
		}
		Double backAmount = mapper.getBackAmount(back);
		if (backAmount + back.getAmount() > outputAmount) {
			throw new RuntimeException(
					"当前退库数量 " + back.getAmount() + " 加上已退库数量 " + backAmount + " 不能大于出库总量 " + outputAmount + "!");
		}
		mapper.add(back);
	}

	public void update(B_BACK back) {
		B_OUTPUT output = new B_OUTPUT();
		output.setBuilder_id(back.getBuilder_id());
		output.setMaterial_id(back.getMaterial_id());
		Double outputAmount = outputMapper.getOutputAmount(output);
		if (outputAmount == 0) {
			throw new RuntimeException("该施工队没有出库该材料，无法退库！");
		}
		Double currAmount = mapper.getBackById(back.getBack_id()).getAmount();
		Double backAmount = mapper.getBackAmount(back);
		if (backAmount - currAmount + back.getAmount() > outputAmount) {
			throw new RuntimeException("当前退库数量 " + back.getAmount() + " 加上已退库数量 " + (backAmount - currAmount)
					+ " 不能大于出库总量 " + outputAmount + "!");
		}
		mapper.update(back);
	}

	public void setDisabled(B_BACK back) {
		mapper.setDisabled(back);
	}

	public void delete(String back_id) {
		mapper.delete(back_id);
	}

	public B_BACK getBackById(String back_id) {
		return mapper.getBackById(back_id);
	}

	public List<LowerCaseKeyMap> getBackList(B_BACK back) {
		return mapper.getBackList(back);
	}
}
